package com.xbongbong.paas.service.team.strategy;

import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.parent.interfaces.TeamStrategy;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailEditLabelDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailUpdateDTO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditCoPerVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditLabelVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.team.TeamAfterFormatDTO;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.team.TeamVerifyDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerUserModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.swing.plaf.basic.BasicScrollPaneUI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 经销商档案
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class DistributorManageTeamStrategy extends AbstractTeamStrategy implements TeamStrategy {

    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private CustomerFocusModel customerFocusModel;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode());
    }

    @Override
    public TeamAfterVerifyDTO verify(TeamVerifyDTO teamVerifyDTO) throws XbbException {
        return super.verifyTeam(teamVerifyDTO);
    }

    @Override
    public TeamAfterVerifyDTO specialVerify(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        return teamAfterVerifyDTO;
    }

    @Override
    public void save(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();
        TeamAfterFormatDTO teamAfterFormatDTO = formatTeam(teamAfterVerifyDTO);

        LinkedHashMap<String, Integer> esWait = judgeTeamEsWait(teamAfterFormatDTO);

        for (Iterator<Map.Entry<String, Integer>> iterator = esWait.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, Integer> entry = iterator.next();
            boolean hasNext = iterator.hasNext();
            switch (entry.getKey()) {
                case TeamMembersConstant.ADD_USER:
                    List<UserTeamEntity> addUserTeamList = teamAfterFormatDTO.getAddUserTeamList();
                    if (CollectionsUtil.isNotEmpty(addUserTeamList)) {
                        List<CustomerUserEntity> customerUserEntityList = new ArrayList<>();
                        try {
                            BeanUtil.copyPropertiesList(addUserTeamList, customerUserEntityList, CustomerUserEntity.class, false);
                        } catch (Exception e) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                        }
                        if (hasNext) {
                            customerUserModel.insertBatch(customerUserEntityList, true);
                        } else {
                            customerUserModel.insertBatch(customerUserEntityList, false);
                        }
                    }
                    break;
                case TeamMembersConstant.DEL_USER:
                    List<UserTeamEntity> delUserTeamList = teamAfterFormatDTO.getDelUserTeamList();
                    if (CollectionsUtil.isNotEmpty(delUserTeamList)) {
                        List<Long> idIn = delUserTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            customerUserModel.batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, null, DelEnum.DELETE.getDel(), WriteRequest.RefreshPolicy.NONE);
                        } else {
                            customerUserModel.batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, null, DelEnum.DELETE.getDel(), WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                        // 删除的要共享取关
                        List<String> useridIn = delUserTeamList.stream().map(UserTeamEntity::getUserId).collect(Collectors.toList());
                        delUserTeamList.forEach(v -> {
                            customerFocusModel.unFocusByUserIdIn( v.getDataId(), corpid, useridIn);
                        });

                    }
                    break;
                case TeamMembersConstant.TO_MAIN_USER:
                    List<UserTeamEntity> updateUserToMainTeamList = teamAfterFormatDTO.getUpdateUserToMainTeamList();
                    if (CollectionsUtil.isNotEmpty(updateUserToMainTeamList)) {
                        List<Long> idIn = updateUserToMainTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            customerUserModel.batchUpdateByUserIdIn(corpid, idIn, updateUserToMainTeamList, BasicConstant.MAIN_USER, DelEnum.NORMAL.getDel(), WriteRequest.RefreshPolicy.NONE);
                        } else {
                            customerUserModel.batchUpdateByUserIdIn(corpid, idIn, updateUserToMainTeamList, BasicConstant.MAIN_USER, DelEnum.NORMAL.getDel(), WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.TO_CO_USER:
                    List<UserTeamEntity> updateUserToCoTeamList = teamAfterFormatDTO.getUpdateUserToCoTeamList();
                    if (CollectionsUtil.isNotEmpty(updateUserToCoTeamList)) {
                        List<Long> idIn = updateUserToCoTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            customerUserModel.batchUpdateCoAndPerByUserIdIn(corpid, idIn, updateUserToCoTeamList, BasicConstant.COOP_USER, false, WriteRequest.RefreshPolicy.NONE);
                        } else {
                            customerUserModel.batchUpdateCoAndPerByUserIdIn(corpid, idIn, updateUserToCoTeamList, BasicConstant.COOP_USER, false, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.UPDATE_USER:
                    List<UserTeamEntity> updateUserTeamMainList = teamAfterFormatDTO.getUpdateUserTeamMainList();
                    if (CollectionsUtil.isNotEmpty(updateUserTeamMainList)) {
                        //这边需要更新团队成员的teamUserId，这个字段是不需要存数据库的，但是es还是需要更新一下更新时间
                        List<Long> idIn = updateUserTeamMainList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            customerUserModel.batchUpdateTeamMainByUserIdIn(corpid, idIn, updateUserTeamMainList, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        } else {
                            customerUserModel.batchUpdateTeamMainByUserIdIn(corpid, idIn, updateUserTeamMainList, WriteRequest.RefreshPolicy.NONE);
                        }
                    }
                    break;
                default:
            }
        }
    }

    @Override
    public void afterSave(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {

    }

    @Override
    public void log(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        super.log(teamAfterVerifyDTO);
    }

    @Override
    public TeamDetailEditCoPerVO editCoPermission(TeamDetailUpdateDTO teamDetailUpdateDTO) throws XbbException {
        return null;
    }

    @Override
    public TeamDetailEditLabelVO editLabel(TeamDetailEditLabelDTO teamDetailEditLabelDTO) throws XbbException {
        return null;
    }

}
